package org.shiro.demo.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.shiro.demo.dao.util.Pagination;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.Administrator;
import org.shiro.demo.entity.Order;
import org.shiro.demo.entity.OrderBuffer;
import org.shiro.demo.entity.OrderDetail;
import org.shiro.demo.entity.OrderProp;
import org.shiro.demo.entity.Product;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.Ticket;
import org.shiro.demo.entity.User;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IOrderBufferService;
import org.shiro.demo.service.IOrderPropService;
import org.shiro.demo.service.IOrderService;
import org.shiro.demo.service.IProductService;
import org.shiro.demo.service.IUserService;
import org.shiro.demo.util.UUIDCreator;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/order")
public class OrderController {

	@Resource(name = "orderService")
	private IOrderService orderService;

	@Resource(name = "orderBufferService")
	private IOrderBufferService orderBufferService;

	@Resource(name = "baseService")
	private IBaseService baseService;
	@Resource
	private IUserService userService;
	@Resource
	private IOrderPropService orderPropService;
	@Resource
	private IProductService productService;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 获取某个用户的订单 订单按照添加订单的逆序,即越完提交订单越前
	 * 
	 * @param userId
	 * @param propId
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/findOrdersByUser")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public Object findByUser(Long userId, Long propId, Integer currentPage, Integer pageSize) {
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();

		// User user = userService.getById(User.class, userId);
		User user = getCurrentUser();
		queryConditions.add(new QueryCondition("user", "=", user));

		// 若propId是null表示拿所有的订单
		if (propId != 0) {
			OrderProp orderProp = orderPropService.getById(OrderProp.class, propId);
			queryConditions.add(new QueryCondition("orderProp", QueryCondition.EQ, orderProp));
		}

		Pagination<Order> pagination = orderService.getPagination(Order.class, queryConditions, "ORDER　BY o.postTime desc", currentPage, pageSize);
		return new ResponseResult(1, "获取用户 " + user.getPhone() + " 的订单成功", pagination);
	}

	/**
	 * 店长查询带提货的订单
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getDiliverOrder")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles(value = "manager")
	public Object getDiliverOrder(@RequestParam(value = "uuid") String uuid) {
		ResponseResult rr = new ResponseResult();

		if (StringUtils.isEmpty(uuid)) {
			rr.setCode(0);
			rr.setInfo("订单号不能为空");
			return rr;
		}

		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("uuid", QueryCondition.EQ, uuid));

		Order order = (Order) orderService.getSingleResult(Order.class, queryConditions);

		if (order == null) {
			rr.setCode(0);
			rr.setInfo("不存在这张订单");
			return rr;
		}

		if (order.getOrderProp().getId() == 2) {
			rr.setCode(1);
			rr.setInfo("success");
			rr.setObject(order);
			return rr;
		}

		rr.setCode(0);
		rr.setInfo("请确定这张订单未被提走");
		return rr;
	}

	/**
	 * 店长===》提取
	 * 
	 * @param uuid
	 * @return
	 */
	@RequestMapping(value = "/dilivery")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles(value = "manager")
	public Object diliveryTheOrder(@RequestParam(value = "uuid") String uuid) {
		ResponseResult rr = new ResponseResult();

		if (StringUtils.isEmpty(uuid)) {
			rr.setCode(0);
			rr.setInfo("订单号不能为空");
			return rr;
		}

		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("uuid", QueryCondition.EQ, uuid));
		Order order = (Order) orderService.getSingleResult(Order.class, queryConditions);
		if (order == null) {
			rr.setCode(0);
			rr.setInfo("不存在这张订单");
			return rr;
		}

		if (order.getOrderProp().getId() != 2L) {
			rr.setCode(0);
			return rr;
		}

		Date bufferTime = new Date();
		// 设置处理订单的店长
		Administrator admin = (Administrator) SecurityUtils.getSubject().getPrincipal();

		order.setOperator(admin.getPhone());
		order.setBufferTime(bufferTime);
		OrderProp orderProp = orderPropService.getById(OrderProp.class, 3L);
		order.setOrderProp(orderProp);

		try {
			orderService.update(order);

			// 增加提货信息
			OrderBuffer ob = new OrderBuffer();
			ob.setBufferTime(bufferTime);
			ob.setOperator(admin.getPhone());
			ob.setOrderType(1);// 正常订单
			ob.setUuid(uuid);
			ob.setBufferDate(bufferTime);
			ob.setMoney(order.getMoney());
			ob.setStoreId(order.getStoreId());// 门店 不做准

			orderBufferService.saveAndCache(admin.getPhone(), sdf.format(bufferTime), ob);// 保存提货信息，，用于后期
																							// 财务报表
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;
	}

	/**
	 * 根据订单的id获取订单的信息
	 * 
	 * @param orderId
	 *            订单id
	 * @return ResponseResult,object为order
	 */
	@RequestMapping(value = "/findById")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public ResponseResult findById(@RequestParam(value = "id") Long orderId) {
		ResponseResult rr = new ResponseResult();

		Order order = orderService.getById(Order.class, orderId);

		User user = getCurrentUser();

		if (user.getId() != order.getUser().getId()) {
			rr.setCode(0);
			rr.setInfo("该订单不属于你");
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(order);
		return rr;
	}

	@RequestMapping(value = "/findByUuid")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public Object findByUuid(@RequestParam(value = "uuid") String uuid) {
		User user = getCurrentUser();
		ResponseResult rr = new ResponseResult();
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("uuid", QueryCondition.EQ, uuid));
		if (uuid.startsWith("o")) {
			Order order = (Order) orderService.getSingleResult(Order.class, queryConditions);
			if (user.getId() != order.getUser().getId()) {
				rr.setCode(0);
				rr.setInfo("该订单不属于你");
				return rr;
			}
			rr.setCode(1);
			rr.setInfo("success");
			rr.setObject(order);
		}else{/// 优惠券
			Ticket order = (Ticket) baseService.getSingleResult(Ticket.class, queryConditions);
			if (user.getId() != order.getUser().getId()) {
				rr.setCode(0);
				rr.setInfo("该订单不属于你");
				return rr;
			}
			rr.setCode(1);
			rr.setInfo("success");
			rr.setObject(order);
		}
		
		return rr;
	}

	/**
	 * 下单 对应的product的货存量要减一。
	 * 
	 * @param description
	 *            下单备注
	 * @param orderDetails
	 *            订单详细信息
	 * @param bufferInterval
	 *            自提时间，值为0 ，1，2
	 * @des:orderDetails是json数据：一个List,每个元素都是OrderDetail类型,需要id,productId,amount,price这些属性.
	 * @return ResponseResult
	 *         [{"amount":1,"id":1,"price":23.0,"product":null,"productId"
	 *         :null}]
	 *         [{"amount":1,"id":1,"price":23.0,"product":null,"productId"
	 *         :null},
	 *         {"amount":1,"id":1,"price":23.0,"product":null,"productId":null}]
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public ResponseResult add(HttpSession session, String description, String payType, String deliveryType, int storeId, int bufferInterval, String orderDetails) {
		Order order = new Order();

		// 描述=>备注
		order.setDescription(description);
		// 设置订单主人为当前登陆的用户.

		User customer = (User) SecurityUtils.getSubject().getPrincipal();
		order.setUser(customer);
		// order.setUser((User) session.getAttribute("user"));
		// 下单时间即为此时此刻
		order.setPostTime(new Date());
		// 交易时间/付款时间此时未定
		order.setDealTime(null);
		// order.setIsSure(false);
		order.setIsPay(false);// 默认未支付
		order.setIsBuffet(true);// 默认是自提
		order.setIsCancel(false);// 默认订单不是取消状态
		order.setBufferInterval(bufferInterval);
		Product product;

		try {
			ObjectMapper ob = new ObjectMapper();
			JavaType javaType = ob.getTypeFactory().constructParametricType(List.class, OrderDetail.class);
			System.out.print("---");
			System.out.print(orderDetails);

			System.out.print("---");

			List<OrderDetail> orderDetailsList = (List<OrderDetail>) ob.readValue(orderDetails, javaType);
			for (OrderDetail orderDetail : orderDetailsList) {
				orderDetail.setOrder(order);
			}

			order.setOrderDetails(new HashSet<OrderDetail>(orderDetailsList));

			double money = 0;
			// price在OrderDetails里面 每一个商品都需要比较！
			for (OrderDetail orderDetail : orderDetailsList) {
				product = productService.getById(Product.class, orderDetail.getProductId());
				// 如果订单中 产品的价格不低于现在的产品价格 产品是激活的 货存数量是够的 ===》 可以下单
				if (orderDetail.getPrice() >= product.getPrice() && product.isStatus() && product.getAmount() - orderDetail.getAmount() >= 0) {

					orderDetail.setPrice(product.getPrice());
					orderDetail.setProduct(product);
					money = money + (orderDetail.getAmount() * orderDetail.getPrice());
				} else {
					return new ResponseResult(-1, "订单信息有误", null);
				}
			}
			// product的或存量要减一 <==> 对应的撤销，要加回去
			for (OrderDetail orderDetail : orderDetailsList) {
				product = productService.getById(Product.class, orderDetail.getProductId());
				product.setAmount(product.getAmount() - orderDetail.getAmount());
			}

			// 设置订单的初始状态
			OrderProp orderProp = new OrderProp();
			orderProp.setId(1L);
			orderProp.setStatus(1);
			order.setOrderProp(orderProp);
			// 设置uuid。。o字母开头+8位uuid+个人id...
			order.setUuid("o" + UUIDCreator.getShortUuid() + customer.getId());
			order.setMoney(money);
			// 设置支付方式
			order.setPayType(payType);
			order.setDeliveryType("自提");
			order.setStoreId(storeId);

			orderService.save(order);

		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "下单失败,订单信息有误.", null);
		}

		return new ResponseResult(1, "下单成功", order);
	}

	/**
	 * 超级管理员查询订单
	 * 
	 * @param pageSize
	 * @param pageNumber
	 * @param orderBy
	 * @param asc
	 * @param propId
	 * @return
	 */
	@RequestMapping(value = "/adminOrders")
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public @ResponseBody Object adminGetOrder(@RequestParam(value = "pageSize") Integer pageSize, //
			@RequestParam(value = "pageNumber") Integer pageNumber, @RequestParam(value = "orderBy", required = false) String orderBy, @RequestParam(value = "asc", required = false) Boolean asc, @RequestParam(value = "propId") long propId) {

		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		OrderProp orderProp = orderPropService.getById(OrderProp.class, propId);
		queryConditions.add(new QueryCondition("orderProp", QueryCondition.EQ, orderProp));

		Pagination<Order> pagination = null;
		if (orderBy != null && asc != null) {
			pagination = orderService.getPagination(Order.class, queryConditions, " order by o." + orderBy + " " + (asc ? " ASC " : " DESC "), pageNumber, pageSize);
		} else {
			pagination = orderService.getPagination(Order.class, queryConditions, null, pageNumber, pageSize);
		}
		return pagination;
	}

	@RequestMapping(value = "/adminOrdersTotal")
	public @ResponseBody long adminGetOrderTotal(@RequestParam(value = "propId") long propId) {
		long recordCount;
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		OrderProp jobProp = orderPropService.getById(OrderProp.class, propId);
		queryConditions.add(new QueryCondition("orderProp", QueryCondition.EQ, jobProp));
		recordCount = orderService.getRecordCount(Order.class, queryConditions);
		return recordCount;
	}

	/**
	 * 超级管理员==》所有的代金券
	 * 
	 * @param pageSize
	 * @param pageNumber
	 * @param orderBy
	 * @param asc
	 * @param propId
	 * @return
	 */
	@RequestMapping(value = "/adminGetTicketOrders")
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public @ResponseBody Object adminGetTicketOrders(@RequestParam(value = "pageSize") Integer pageSize, //
			@RequestParam(value = "pageNumber") Integer pageNumber, @RequestParam(value = "orderBy", required = false) String orderBy, @RequestParam(value = "asc", required = false) Boolean asc, @RequestParam(value = "propId") long propId) {

		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		OrderProp orderProp = orderPropService.getById(OrderProp.class, propId);
		queryConditions.add(new QueryCondition("orderProp", QueryCondition.EQ, orderProp));

		Pagination<Ticket> pagination = null;
		if (orderBy != null && asc != null) {
			pagination = orderService.getPagination(Ticket.class, queryConditions, " order by o." + orderBy + " " + (asc ? " ASC " : " DESC "), pageNumber, pageSize);
		} else {
			pagination = orderService.getPagination(Ticket.class, queryConditions, null, pageNumber, pageSize);
		}
		return pagination;
	}

	/**
	 * 根据订单的id删除订单
	 * 
	 * @param orderId
	 *            订单id
	 * @return ResponseResult
	 */
	@RequestMapping(value = "/cancelOrder")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public ResponseResult cancelOrder(Long orderId) {
		// 检查订单 是不是这个顾客的。
		ResponseResult rr = new ResponseResult();
		Subject currentUser = SecurityUtils.getSubject();
		User user = (User) currentUser.getPrincipal();

		String phone = user.getPhone();
		try {

			Order order = orderService.getById(Order.class, orderId);
			if (!order.getUser().getPhone().equals(phone)) {
				rr.setInfo("订单不属于您");
				rr.setCode(0);
				return rr;
			}
			Set<OrderDetail> orderDetails = order.getOrderDetails();
			for (OrderDetail orderDetail : orderDetails) {
				Product product = productService.getById(Product.class, orderDetail.getProductId());
				product.setAmount(product.getAmount() + orderDetail.getAmount());
				productService.update(product);
			}
			// 取消订单
			OrderProp orderProp = order.getOrderProp();
			orderProp.setId(4L);
			orderProp.setStatus(4);
			order.setOrderProp(orderProp);

			orderService.update(order);

		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;
	}

	private User getCurrentUser() {
		// 设置订单主人为当前登陆的用户.
		Subject currentUser = SecurityUtils.getSubject();
		User customer = (User) currentUser.getPrincipal();
		return customer;
	}

	// //
	// -------------------------------------------代金券-------------------------------------------
	/**
	 * 
	 * 
	 * @param description
	 *            代金券 下单备注
	 * @return ResponseResult
	 *         [{"amount":1,"id":1,"price":23.0,"product":null,"productId" :0}]
	 */
	@RequestMapping(value = "/addTicket")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public ResponseResult addTicket(HttpSession session, String description, String payType, double money) {
		User customer = getCurrentUser();
		if (money < 0) {
			return new ResponseResult(0, " 金额小于0", null);
		}
		if (!payType.equals("tenpay") && !payType.equals("alipay")) {
			return new ResponseResult(0, " 支付方式有误", null);
		}
		/**
		 * 从数据库中找到已经存在的ticket
		 */
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("user", QueryCondition.EQ, customer));
		OrderProp op1 = new OrderProp();
		op1.setId(1L);
		queryConditions.add(new QueryCondition("orderProp", QueryCondition.EQ, op1));
		Ticket ticket = (Ticket) baseService.getSingleResult(Ticket.class, queryConditions);
		if (ticket == null) {
			// 不存在 已经未支付的 ticket，新建一个
			ticket = new Ticket();
			ticket.setUuid("t" + UUIDCreator.getShortUuid() + customer.getId());
		} else {// 存在已经下单的 ticket
				// 下单的ticket 的uuid 可能已经生成过 微信的prepayid 了，这时候 就是删除这条记录。
				// 因为生成过prepay order的uuid 不能再 调用微信的 prepay接口，会报错：商户订单号重复
			if (!ticket.getUuid().endsWith("t")) {// 未付款，并且不是以t结尾（说明不是免费代金券），说明这是正常订单，可以删除
				baseService.delete(Ticket.class, ticket.getId());
			}
			// 重新生成 新的 ticket
			ticket = new Ticket();
			ticket.setUuid("t" + UUIDCreator.getShortUuid() + customer.getId());
		}

		// 描述=>备注
		ticket.setDescription(description);
		ticket.setUser(customer);
		// 下单时间即为此时此刻
		ticket.setPostTime(new Date());
		// 交易时间/付款时间此时未定
		ticket.setDealTime(null);
		ticket.setIsPay(false);// 默认未支付
		ticket.setIsBuffet(true);// 默认是自提
		ticket.setIsCancel(false);// 默认订单不是取消状态
		try {
			// 设置订单的初始状态
			OrderProp orderProp = new OrderProp();
			orderProp.setId(1L);
			orderProp.setStatus(1);
			ticket.setOrderProp(orderProp);
			// 设置uuid。。t开头+8位uuid+个人id。
			ticket.setMoney(money);
			ticket.setDiscount(0.98);// 统一0.98
			// 设置支付方式
			ticket.setPayType(payType);
			ticket.setDeliveryType("自提");
			ticket.setBufferInterval(0);// 代金券 默认当天提
			baseService.update(ticket);// 可能新建，可能更新
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "下单失败,订单信息有误.", null);
		}
		return new ResponseResult(1, "下单成功", ticket);
	}

	/**
	 * 获取某个用户的代金券。代金券按照添加代金券的逆序,即越晚提交订单越前 只得到 那些支付的。跟那些使用过的。 prop=2 或者 3
	 * 
	 * 可能有一个prop=1的情况，不存在prop=4的状态。
	 * 
	 * @param userId
	 * @param propId
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/getTickets")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public Object getTickets(long propId, int currentPage, int pageSize) {
		if (propId < 2 || propId > 4) {
			return new ResponseResult(0, "状态错误", null);
		}
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();

		User user = getCurrentUser();
		queryConditions.add(new QueryCondition("user", QueryCondition.EQ, user));
		OrderProp prop = new OrderProp();
		prop.setId(propId);
		queryConditions.add(new QueryCondition("orderProp", QueryCondition.EQ, prop));

		Pagination<Ticket> pagination = baseService.getPagination(Ticket.class, queryConditions, "ORDER　BY o.postTime desc", currentPage, pageSize);
		return new ResponseResult(1, "获取用户 " + user.getPhone() + " 的 代金券成功", pagination);
	}

	/**
	 * 根据订单的id获取订单的信息
	 * 
	 * @param id
	 *            订单id
	 * @return ResponseResult,object为order
	 */
	@RequestMapping(value = "/findTicketById")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public ResponseResult findTicketById(@RequestParam(value = "id") Long id) {
		ResponseResult rr = new ResponseResult();

		Ticket order = baseService.getById(Ticket.class, id);

		User user = getCurrentUser();

		if (user.getId() != order.getUser().getId()) {
			rr.setCode(0);
			rr.setInfo("该订单不属于你");
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(order);
		return rr;
	}

	@RequestMapping(value = "/findTicketByUuid")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public Object findTicketByUuid(@RequestParam(value = "uuid") String uuid) {
		ResponseResult rr = new ResponseResult();
		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("uuid", QueryCondition.EQ, uuid));
		Ticket order = (Ticket) baseService.getSingleResult(Ticket.class, queryConditions);

		User user = getCurrentUser();
		if (user.getId() != order.getUser().getId()) {
			rr.setCode(0);
			rr.setInfo("该订单不属于你");
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(order);
		return rr;
	}

	/**
	 * 店长查询 代金券
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getTicketOrder")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles(value = "manager")
	public Object getTicketOrder(@RequestParam(value = "uuid") String uuid) {
		ResponseResult rr = new ResponseResult();

		if (StringUtils.isEmpty(uuid)) {
			rr.setCode(0);
			rr.setInfo("订单号不能为空");
			return rr;
		}

		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("uuid", QueryCondition.EQ, uuid));

		Ticket ticket = (Ticket) baseService.getSingleResult(Ticket.class, queryConditions);

		if (ticket == null) {
			rr.setCode(0);
			rr.setInfo("不存在这张订单");
			return rr;
		}

		if (ticket.getOrderProp().getId() == 2) {
			rr.setCode(1);
			rr.setInfo("success");
			rr.setObject(ticket);
			return rr;
		}

		rr.setCode(0);
		rr.setInfo("请确认这张订单未被提");
		return rr;
	}

	/**
	 * 店长===》代金券 提取
	 * 
	 * @param uuid
	 * @return
	 */
	@RequestMapping(value = "/diliveryTicket")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles(value = "manager")
	public Object diliveryTicket(@RequestParam(value = "uuid") String uuid) {
		ResponseResult rr = new ResponseResult();

		if (StringUtils.isEmpty(uuid)) {
			rr.setCode(0);
			rr.setInfo("不存在这张订单");
			return rr;
		}

		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("uuid", QueryCondition.EQ, uuid));
		Ticket ticket = (Ticket) baseService.getSingleResult(Ticket.class, queryConditions);
		if (ticket == null) {
			rr.setCode(0);
			return rr;
		}

		if (ticket.getOrderProp().getId() != 2) {
			rr.setCode(0);
			rr.setInfo("请检查这张订单是否为未提货");
			return rr;
		}

		Date bufferTime = new Date();
		Subject currentManager = SecurityUtils.getSubject();
		Administrator manager = (Administrator) currentManager.getPrincipal();
		String managerPhone = manager.getPhone();

		OrderProp orderProp = orderPropService.getById(OrderProp.class, 3L);
		ticket.setOrderProp(orderProp);
		ticket.setBufferTime(bufferTime);
		ticket.setOperator(managerPhone);

		try {
			baseService.update(ticket);

			// 增加提货信息
			OrderBuffer ob = new OrderBuffer();
			ob.setBufferTime(bufferTime);
			ob.setOperator(managerPhone);
			ob.setOrderType(3);// 代金订单
			ob.setUuid(uuid);
			ob.setBufferDate(bufferTime);
			ob.setMoney(ticket.getMoney());
			// ob.setStoreId();// 门店 不做准

			orderBufferService.saveAndCache(managerPhone, sdf.format(bufferTime), ob);// 保存提货信息，，用于后期
																						// 财务报表

		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject(null);
		return rr;
	}

	/**
	 * 店长查询自己处理的 提货券
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getHandledOrder")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles(value = "manager")
	public Object getHandledOrder(@RequestParam(value = "pageSize") Integer pageSize, //
			@RequestParam(value = "pageNumber") Integer pageNumber, @RequestParam(value = "orderBy", required = false) String orderBy, @RequestParam(value = "asc", required = false) Boolean asc) {

		Subject currentManager = SecurityUtils.getSubject();
		Administrator managerString = (Administrator) currentManager.getPrincipal();
		String phone = managerString.getPhone();

		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("operator", QueryCondition.EQ, phone));

		Pagination<Order> pagination = null;

		if (orderBy != null && asc != null) {
			pagination = baseService.getPagination(Order.class, queryConditions, " order by o." + orderBy + " " + (asc ? " ASC " : " DESC "), pageNumber, pageSize);
		} else {
			pagination = baseService.getPagination(Order.class, queryConditions, "ORDER BY o.postTime DESC", pageNumber, pageSize);
		}

		return pagination;
	}

	/**
	 * 店长查询自己处理的 代金券
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getHandledTicketOrder")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles(value = "manager")
	public Object getHandledTicketOrder(@RequestParam(value = "pageSize") Integer pageSize, @RequestParam(value = "pageNumber") Integer pageNumber, @RequestParam(value = "orderBy", required = false) String orderBy, @RequestParam(value = "asc", required = false) Boolean asc) {

		Subject currentManager = SecurityUtils.getSubject();
		Administrator managerString = (Administrator) currentManager.getPrincipal();
		String phone = managerString.getPhone();

		List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
		queryConditions.add(new QueryCondition("operator", QueryCondition.EQ, phone));

		Pagination<Ticket> pagination = null;

		if (orderBy != null && asc != null) {
			pagination = baseService.getPagination(Ticket.class, queryConditions, " order by o." + orderBy + " " + (asc ? " ASC " : " DESC "), pageNumber, pageSize);
		} else {
			pagination = baseService.getPagination(Ticket.class, queryConditions, "ORDER BY o.postTime DESC", pageNumber, pageSize);
		}

		return pagination;
	}

}
